package com.gyg.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.gyg.constant.CloudConstant;
import com.gyg.dao.CloudSpaceMapper;
import com.gyg.domain.*;
import com.gyg.returns.RespCode;
import com.gyg.returns.RespEntity;
import com.gyg.returns.RespTable;
import com.gyg.service.*;
import com.gyg.utils.TimeUtilCustomize;
import com.gyg.vo.result.SpaceFileResult;
import com.gyg.vo.result.SpaceUserResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 云盘空间表 服务实现类
 * </p>
 *
 * @author gyg
 * @since 2021-04-14
 */
@Service
@Slf4j
public class CloudSpaceServiceImpl extends ServiceImpl<CloudSpaceMapper, CloudSpace> implements CloudSpaceService {

    @Autowired
    private CloudUserService cloudUserService;

    @Autowired
    private CloudPictureService cloudPictureService;

    @Autowired
    private CloudDocumentService cloudDocumentService;

    @Autowired
    private CloudAudioService cloudAudioService;

    @Autowired
    private CloudVideoService cloudVideoService;

    @Override
    public RespTable<List<SpaceUserResult>> spaceUserList(Integer page, Integer limit, String username) {
        QueryWrapper<CloudUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.lambda().eq(CloudUser::getUsername, username);
        }

        IPage<CloudUser> iPage = new Page<>(page, limit);
        IPage<CloudUser> pg = cloudUserService.page(iPage, queryWrapper);

        //数据组装
        List<SpaceUserResult> spaceUserResultList = dataPackage(pg.getRecords());

        return new RespTable<>(RespCode.OK, spaceUserResultList, pg.getTotal());
    }

    private List<SpaceUserResult> dataPackage(List<CloudUser> records) {
        if (CollectionUtil.isEmpty(records)) {
            return new ArrayList<>();
        }

        List<SpaceUserResult> spaceUserResultList = Lists.newArrayList();
        for (CloudUser cloudUser : records) {
            QueryWrapper<CloudSpace> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CloudSpace::getUserId, cloudUser.getId());
            CloudSpace cloudSpace = baseMapper.selectOne(queryWrapper);

            //云盘容量占用率
            BigDecimal percent = new BigDecimal(cloudSpace.getSpaceUsedByte()).multiply(new BigDecimal(100))
                    .divide(new BigDecimal(cloudSpace.getSpaceTotalByte()), 2, BigDecimal.ROUND_HALF_UP);

            //数据组装
            SpaceUserResult spaceUserResult = SpaceUserResult.builder()
                    .id(cloudUser.getId())
                    .username(cloudUser.getUsername())
                    .name(cloudUser.getName())
                    .percent(percent + "")
                    .build();

            spaceUserResultList.add(spaceUserResult);
        }

        return spaceUserResultList;
    }

    @Override
    public RespEntity<SpaceFileResult> spaceFileList() {

        //最近7日日期集合 包含今日
        List<String> recentSevenDayList = TimeUtilCustomize.getRecentSevenDayList();
        //今日
        String today = TimeUtilCustomize.parseDateToStr(TimeUtilCustomize.DATE_MD_FORMAT, new Date());

        //数据封装
        List<String> dateList = Lists.newArrayList();
        List<String> pictureList = Lists.newArrayList();
        List<String> documentList = Lists.newArrayList();
        List<String> audioList = Lists.newArrayList();
        List<String> videoList = Lists.newArrayList();
        dateList.add("日期");
        pictureList.add("图片");
        documentList.add("文档");
        audioList.add("音频");
        videoList.add("视频");

        for (String date : recentSevenDayList) {
            //计算图片容量占用之和
            QueryWrapper<CloudPicture> pictureQueryWrapper = new QueryWrapper<>();
            pictureQueryWrapper.select("SUM(picture_byte) AS picture_byte");
            pictureQueryWrapper.lambda().eq(CloudPicture::getDeleted, 0)
                    .between(CloudPicture::getPictureTime, CloudConstant.OPEN_TIME, date);
            CloudPicture cloudPicture = cloudPictureService.getOne(pictureQueryWrapper);
            BigDecimal pictureSpaceMB = new BigDecimal(cloudPicture.getPictureByte())
                    .divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
            pictureList.add(pictureSpaceMB + "");

            //计算文档容量占用之和
            QueryWrapper<CloudDocument> documentQueryWrapper = new QueryWrapper<>();
            documentQueryWrapper.select("SUM(document_byte) AS document_byte");
            documentQueryWrapper.lambda().eq(CloudDocument::getDeleted, 0)
                    .between(CloudDocument::getDocumentTime, CloudConstant.OPEN_TIME, date);
            CloudDocument cloudDocument = cloudDocumentService.getOne(documentQueryWrapper);
            BigDecimal documentSpaceMB = new BigDecimal(cloudDocument.getDocumentByte())
                    .divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
            documentList.add(documentSpaceMB + "");

            //计算音频容量占用之和
            QueryWrapper<CloudAudio> audioQueryWrapper = new QueryWrapper<>();
            audioQueryWrapper.select("SUM(audio_byte) AS audio_byte");
            audioQueryWrapper.lambda().eq(CloudAudio::getDeleted, 0)
                    .between(CloudAudio::getAudioTime, CloudConstant.OPEN_TIME, date);
            CloudAudio cloudAudio = cloudAudioService.getOne(audioQueryWrapper);
            BigDecimal audioSpaceMB = new BigDecimal(cloudAudio.getAudioByte())
                    .divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
            audioList.add(audioSpaceMB + "");

            //计算视频容量占用之和
            QueryWrapper<CloudVideo> videoQueryWrapper = new QueryWrapper<>();
            videoQueryWrapper.select("SUM(video_byte) AS video_byte");
            videoQueryWrapper.lambda().eq(CloudVideo::getDeleted, 0)
                    .between(CloudVideo::getVideoTime, CloudConstant.OPEN_TIME, date);
            CloudVideo cloudVideo = cloudVideoService.getOne(videoQueryWrapper);
            BigDecimal videoSpaceMB = new BigDecimal(cloudVideo.getVideoByte())
                    .divide(new BigDecimal(1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);
            videoList.add(videoSpaceMB + "");
        }

        //日期格式处理 yyyy-MM-dd HH:mm:ss --> MM-dd
        recentSevenDayList = recentSevenDayList.stream()
                .map(date -> date.split("\\s+")[0].substring(5))
                .collect(Collectors.toList());
        dateList.addAll(recentSevenDayList);

        return new RespEntity<>(RespCode.SUCCESS, new SpaceFileResult(today, dateList,
                pictureList, documentList, audioList, videoList));
    }

    @Override
    public RespEntity<String> spaceCloud() {
        //图片占用总容量
        QueryWrapper<CloudPicture> pictureQueryWrapper = new QueryWrapper<>();
        pictureQueryWrapper.select("SUM(picture_byte) AS picture_byte");
        CloudPicture cloudPicture = cloudPictureService.getOne(pictureQueryWrapper);

        //文档占用总容量
        QueryWrapper<CloudDocument> documentQueryWrapper = new QueryWrapper<>();
        documentQueryWrapper.select("SUM(document_byte) AS document_byte");
        CloudDocument cloudDocument = cloudDocumentService.getOne(documentQueryWrapper);

        //音频占用总容量
        QueryWrapper<CloudAudio> audioQueryWrapper = new QueryWrapper<>();
        audioQueryWrapper.select("SUM(audio_byte) AS audio_byte");
        CloudAudio cloudAudio = cloudAudioService.getOne(audioQueryWrapper);

        //视频占用总容量
        QueryWrapper<CloudVideo> videoQueryWrapper = new QueryWrapper<>();
        videoQueryWrapper.select("SUM(video_byte) AS video_byte");
        CloudVideo cloudVideo = cloudVideoService.getOne(videoQueryWrapper);

        //云盘总占用量 含用户删除的文件 单位：B
        BigDecimal totalUsedB = new BigDecimal(cloudPicture.getPictureByte())
                .add(new BigDecimal(cloudDocument.getDocumentByte()))
                .add(new BigDecimal(cloudAudio.getAudioByte()))
                .add(new BigDecimal(cloudVideo.getVideoByte()));

        //单位转化为 GB
        BigDecimal totalUsedGB = totalUsedB
                .divide(new BigDecimal(1024 * 1024 * 1024), 2, BigDecimal.ROUND_HALF_UP);

        return new RespEntity<>(RespCode.SUCCESS, totalUsedGB + "");
    }
}
